﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using VmcRemote.Common;
using System.Net.Sockets;

namespace VmcRemote.Common
{
    [Description("TCP")]
    public class TcpConnection : ConnectionBase
    {
        TcpClient tcpServer;
        NetworkStream tcpStream;

        public TcpConnection(string host, int port) : base(host, port) { }
        public TcpConnection(string host, int port, int inactivityTimeout) : base(host, port, inactivityTimeout) { }

        protected override bool Connect()
        {
            bool connected = false;
            try
            {
                tcpServer = new TcpClient(Host, Port);
                if (tcpServer != null)
                    connected = true;
            }
            catch { }
            return connected;
        }

        protected override bool Disconnect()
        {
            bool disconnected = false;
            if (tcpStream != null)
            {
                tcpStream.Close();
                tcpStream.Dispose();
                tcpStream = null;
            }
            if (tcpServer != null)
            {
                tcpServer.Close();
                tcpServer = null;
                disconnected = true;
            }
            return disconnected;
        }

        protected override void Send(byte[] bytes)
        {
            if (tcpStream == null) tcpStream = tcpServer.GetStream();
            tcpStream.Write(bytes, 0, bytes.Length);
            tcpStream.Flush();
        }
    }
}
